package com.example.vw.tabletest.fragment;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import com.example.vw.tabletest.R;
import com.example.vw.tabletest.bean.ReportInfo;
import com.example.vw.tabletest.util.Constant;
import com.example.vw.tabletest.util.Setting;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import static com.example.vw.tabletest.util.Constant.FUNCTIONID_LOADDATA;
import static com.example.vw.tabletest.util.Constant.OPERATION_LOADDATA;
import static com.example.vw.tabletest.util.Constant.URL_TABLE_FORMAT;

public class ExcelsPagerFragment  extends Fragment {

    private WebView mWebTable;
    private WebViewClient refreshTableClient;//携带样式和数据进行页面刷新的WebViewClient
    private Button mBtPhoto; // 查看照片
    private ReportInfo mReport;
    private String mFcode;
    private int mIndex=-1;//当前fragemnt在pager中的顺序号
    private ILoadWebView mLoadWebView= null;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //获得传递的参数
        Bundle arguments = getArguments();
        mReport = new ReportInfo();
        mReport.setId(arguments.getString(Constant.KEY_ID));
        mReport.setText(arguments.getString(Constant.KEY_TEXT));
        mReport.setUrl(arguments.getString(Constant.KEY_URL));
        mFcode = arguments.getString(Constant.KEY_FCODE);
        mIndex = arguments.getInt(Constant.INDEX_TABEL);

        refreshTableClient = new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
//                mWebTable.loadUrl(url);
//                view.evaluateJavascript("javascript:load('1538235454853', '510122106200001', 2018, 4, '278_1')",null);

            }
        };
    }



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_excel, null);
        mBtPhoto = (Button) view.findViewById(R.id.bt_photo);
        mBtPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // todo 查看照片
            }
        });
        mWebTable = (WebView) view.findViewById(R.id.web_table);

        try {
/*

            mWebTable.setWebViewClient(new WebViewClient(){

                //webview不往浏览器跳转
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }

                @Override
                public void  onPageStarted(WebView view, String url, Bitmap favicon) {
                    //设定加载开始的操作
                    // 如可以得到当前的URL
                    //current_url=view.getUrl();
                }
                @Override
                public void onPageFinished(WebView view, String url) {
                    //设定加载结束的操作
                }

//                @Override
//                public boolean onLoadResource(WebView view, String url) {
//                    //设定加载资源的操作,在加载页面资源时会调用，每一个资源（比如图片）的加载都会调用一次。
//                }
                //加载页面的服务器出现错误时（如404）调用 使用自定义的错误界面 更符合软件的整体设计风格
                //步骤1：写一个html文件（error_handle.html），用于出错时展示给用户看的提示页面
                //步骤2：将该html文件放置到代码根目录的assets文件夹下
                //步骤3：复写WebViewClient的onRecievedError方法
                //该方法传回了错误码，根据错误类型可以进行不同的错误分类处理
//                @Override
//                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
//                    switch(errorCode){
//                        case HttpStatus.SC_NOT_FOUND:
//                            view.loadUrl("file:///android_assets/error_handle.html");
//                            break;
//                    }
//                }

                //处理https请求
                @Override
                public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                    handler.proceed();    //表示等待证书响应
                    // handler.cancel();      //表示挂起连接，为默认方式
                    // handler.handleMessage(null);    //可做其他处理
                }
            });
*/
            mWebTable.setWebChromeClient(new myChromeClient());

            //webView初始化
            WebSettings webSettings = mWebTable.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
            webSettings.setAllowContentAccess(true);
            webSettings.setAppCacheEnabled(true);
            webSettings.setUseWideViewPort(true);
            webSettings.setDomStorageEnabled(true);
            webSettings.setDatabaseEnabled(true);
            webSettings.setAppCacheEnabled(true);
            webSettings.setLoadWithOverviewMode(true);
            webSettings.setSupportZoom(true);
            webSettings.setBuiltInZoomControls(true);
            webSettings.setDisplayZoomControls(false);
            webSettings.setLoadsImagesAutomatically(true);//自动加载图片
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
            webSettings.setAllowFileAccessFromFileURLs(true);
            webSettings.setAllowUniversalAccessFromFileURLs(true);
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            webSettings.setDefaultTextEncodingName("utf-8");
            webSettings.setSupportMultipleWindows(true);
            mWebTable.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
            mWebTable.setHorizontalScrollBarEnabled(true);
            mWebTable.setInitialScale(100);

            try {
                if (Build.VERSION.SDK_INT >= 16) {
                    Class<?> clazz = mWebTable.getSettings().getClass();
                    Method method = clazz.getMethod(
                            "setAllowUniversalAccessFromFileURLs", boolean.class);
                    if (method != null) {
                        method.invoke(mWebTable.getSettings(), true);
                    }
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }


            mWebTable.clearCache(true);
            // 设置js和Android的交互
//            mWebTable.addJavascriptInterface(this, "excel");

////            String url = "http://211.103.218.91:8095/appdemo.html?table=1538235454853&catalogID=510122106200001&year=2018&period=4&userID=278_1";
////            String url = "https://cn.bing.com/search?q=%E6%AD%BB%E7%A5%9E&qs=n&form=QBLH&sp=-1&pq=%E6%AD%BB%E7%A5%9E&sc=8-2&sk=&cvid=5A819FF69CE84CD49848F60DEE556EF4";
////            String url = String.format(urlFormat,15)
////            String url = "file:///android_asset/tj_new/appdemo.html";
            String url = String.format(URL_TABLE_FORMAT,
                    mReport.getId(),
                    mFcode,
                    Setting.YEAR,
                    Setting.PERIOD,
                    Setting.USER.getId(),
                    OPERATION_LOADDATA,
                    FUNCTIONID_LOADDATA,
                    Setting.USER.getNameTAG()
                    );
            mWebTable.loadUrl(url);
//            mWebTable.loadUrl(mReport.getUrl());
//            mWebTable.setWebViewClient(refreshTableClient);
//            loadTableRefresh("测试");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return view;
    }


    /**
     * 用于后台读取excel文件并绘制网页的异步线程
     */
    private class InitTableTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... params) {
            // 不需要读取数据，所以这里什么也不做
            return null;
        }

        @Override
        protected void onPostExecute(final String data) {
//            mWebTable.loadUrl(url);
            loadTableRefresh("测试");
        }

        /**
         * 刷新前端web界面
         * @param tableId
         */
        private void loadTableRefresh(final String tableId){
            Toast.makeText(ExcelsPagerFragment.this.getContext(), tableId,Toast.LENGTH_SHORT).show();
            mWebTable.post(new Runnable() {
                @Override
                public void run() {
//                mWebTable.setWebViewClient(refreshTableClient);
                }
            });
        }
    }

    /*private class MyWebViewClient extends WebViewClient{
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url){

            if(Uri.parse(url).getHost().equals(www.example.com)){
                    return false;
                }
                // Otherwise, the link is not for a page on my site, so launch
                // another Activity that handles URLs
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
        }
    }*/


    public interface ILoadWebView {
        /**
         * 当前fragment内浏览器进度更新进度变化
         * @param Index fragment在pager中的顺序号
         * @param newProgress 更新进度
         */
        void onProgressChanged(int Index, int newProgress);
    }

    class myChromeClient extends WebChromeClient {


        @Override
        public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
            super.onShowCustomView(view, callback);
            Log.e("tag", "on Show Custom View >>>>>webView");

        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if(mLoadWebView!=null){
                mLoadWebView.onProgressChanged(mIndex,newProgress);
            }
        }
    }


    /**
     * 设置浏览器更新时主activity的响应
     * @param onLoadWebView
     */
    public void setOnLoadWebView(ILoadWebView onLoadWebView){
        mLoadWebView = onLoadWebView;
    }

    /**
     * 网页回退
     * @return 网页回退成功返回true，否则返回false
     */
    public boolean goBack(){
        if(mWebTable.canGoBack()){
            mWebTable.goBack();
            return true;
        }
        return false;
    }

}
